<template>
  <div class="reservation-system">
    <!-- 导航 -->
    <el-steps
      :active="activeStep"
      align-center
      class="steps"
    >
      <el-step title="选择时间和包厢" />
      <!-- <el-step title="选择时间" /> -->
      <el-step title="确认信息" />
    </el-steps>

    <!-- 步骤内容 -->
    <div
      class="reservation-content"
      v-if="activeStep === 1"
    >
      <!-- 第一步：包厢选择 -->
      <div
        class="button-group"
        v-if="!activeName"
      >

        <el-button
          style="color:rgb(0, 53, 140)"
          class="action-button"
          @click="activeName = '预约';handleTabClick()"
        >
          <span class="button-content">
            <el-icon class="icon">
              <AlarmClock />
            </el-icon>
            <div class="button-text">
              <h2>预约</h2>
            </div>
          </span>
        </el-button>

        <el-button
          style="color:rgb(0, 53, 140)"
          class="action-button"
          @click="activeName = '补录';handleTabClick()"
        >
          <span class="button-content">
            <el-icon class="icon">
              <DocumentAdd />
            </el-icon>
            <div class="button-text">
              <h2>补录</h2>
            </div>
          </span>
        </el-button>

        <!-- <el-button
          type="success"
          class="action-button"
          @click="navigateTo('history')"
        >
          <span class="button-content">
            <el-icon class="icon">
              <List />
            </el-icon>
            <div class="button-text">
              <h2>查看历史订单</h2>
              <p>查询和管理已有订单</p>
            </div>
          </span>
        </el-button> -->

        <!-- <el-button
          type="success"
          class="action-button"
          @click="navigateTo('roomHistory')"
        >
          <span class="button-content">
            <el-icon class="icon">
              <List />
            </el-icon>
            <div class="button-text">
              <h2>查看包厢预约历史</h2>
              <p>查询包厢预约历史</p>
            </div>
          </span>
        </el-button> -->

      </div>

      <div
        v-show="activeStep === 1"
        v-if="activeName"
        class="step step1"
      >
        <h3>选择时间({{activeName}})</h3>

        <el-tree-select
          v-model="reservationDate"
          :data="reservationDateOptions"
          :render-after-expand="false"
          @change="handleDateChange"
          style="width: 240px;"
          size="large"
          placeholder=""
        >
          <template #label="{ label, value }">
            <span style="">{{ label }}</span>
          </template>
          <template #default="{ data: { label } }">
            <span style="">{{ label }}</span>
          </template>
        </el-tree-select>

        <h3>选择包厢类型({{activeName}})</h3>

        <div
          class="package-grid"
          style="background-color: #f5f7fa;"
        >
          <el-card
            v-for="pkg in packages"
            :key="pkg.BX_ID"
            :class="['package-card', { 'selected': selectedPackage?.BX_ID === pkg.BX_ID },]"
            @click="selectPackage(pkg);"
          >
            <div class="package-content">
              <img
                :src="imgList[Number(pkg.BX_ID)]"
                style="width: 100%;height: 100%;"
              />
              <!-- <el-tag
                v-if="pkg.DISABLED == '1'"
                type="danger"
                class="feature-tag"
                size="large"
              >
                {{ '当前不可用' }}
              </el-tag> -->
              <h4>{{ pkg.NAME }}</h4>
              <div class="package-details">
                <div class="detail-item">
                  <el-icon>
                    <User />
                  </el-icon>
                  <!-- <span>{{ pkg.CAPACITY }}人</span> -->
                  <div>建议就餐人数:{{ pkg.RECOMMEND }} </div>
                  <!-- <div>建议就餐人数:{{ pkg.RECOMMEND }},已被预定 </div> -->
                </div>
                <div class="detail-item">
                  <el-icon>
                    <Close v-if="pkg.BX_RECORD_ID" />
                    <Check v-else />
                  </el-icon>
                  <span v-if="pkg.BX_RECORD_ID"> {{'已被预定'}} </span>
                  <span v-else> {{'可预定'}} </span>
                </div>
              </div>

              <!-- <el-tag
                v-for="f in pkg.FEATURES"
                :key="f"
                type="info"
                class="feature-tag"
              >
                {{ f }}
              </el-tag> -->
            </div>
          </el-card>
        </div>
      </div>

      <!-- 第二步：时间选择 -->
      <!-- <div
        v-show="activeStep === 2"
        class="step step2"
      >
        <div class="datetime-picker">
          <el-date-picker
            v-model="reservationDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
          />
          <el-tree-select
            v-model="reservationDate"
            :data="reservationDateOptions"
            :render-after-expand="false"
            style="width: 240px"
            size="large"
          />
          <time-range-selector
            :disabled-ranges="disabledTimes"
            @change="handleTimeChange"
          />
          <el-time-select
            v-model="reservationTime"
            :max-time="maxTime"
            start="10:00"
            step="00:30"
            end="22:00"
            placeholder="选择时间"
          />
        </div> -->
      <!-- <div class="time-slots">
          <el-tag
            v-for="slot in timeSlots"
            :key="slot"
            :type="selectedTime === slot ? 'primary' : 'info'"
            class="time-tag"
            @click="selectTime(slot)"
          >
            {{ slot }}
          </el-tag>
        </div> -->
    </div>

    <!-- 第三步：信息确认 -->
    <div
      v-if="activeStep === 2"
      class="step step3"
    >
      <el-descriptions
        border
        :column="1"
        size="large"
        :label-width="60"
      >
        <el-descriptions-item label="包厢类型">
          <span style="">{{ selectedPackage.NAME }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="预约时间">
          <span style=""> {{ formattedDateTime }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="用餐人数">
          <el-input-number
            v-model="guests"
            :min="selectedPackage.minGuests"
            :max="selectedPackage.maxGuests"
            controls-position="right"
            size="large"
            style="width:150px"
          />
          <span>
            ({{ selectedPackage.RECOMMEND }}人)
          </span>
          <!-- <div>
            ({{ selectedPackage.RECOMMEND }}人)
          </div> -->
        </el-descriptions-item>

        <el-descriptions-item
          label="消费标准"
          style=""
        >
          <el-select
            v-model="selectedPackage.BX_BZ"
            size="large"
            placeholder=""
          >
            <el-option
              v-for="item in selectedPackage.FEATURES"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-descriptions-item>

        <el-descriptions-item label="客户名称">
          <el-input
            v-model="DW"
            style=""
          />
        </el-descriptions-item>
        <el-descriptions-item label="用餐部门">
          <el-select
            v-model="YCBM1"
            size="large"
            placeholder="一级部门"
            @change="YCBM1Changed"
          >
            <el-option
              v-for="item in YCBM_options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <el-select
            v-model="YCBM2"
            size="large"
            placeholder="二级部门"
          >
            <el-option
              v-for="item in YCBM_options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="审批人">
          <el-select
            v-model="SP_ID"
            size="large"
            disabled
          >
            <el-option
              v-for="item in SP_ID_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

        </el-descriptions-item>

        <el-descriptions-item label="成本中心">
          <el-select
            v-model="CBZX"
            size="large"
          >
            <el-option
              v-for="item in CBZX_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          <el-autocomplete
            v-model="LXR"
            :fetch-suggestions="lxrQuerySearch"
            clearable
          />
          <!-- <el-input
            v-model="LXR"
            style=""
          /> -->
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          <!-- <el-input
            v-model="phone"
            style=""
          /> -->
          <el-autocomplete
            v-model="phone"
            :fetch-suggestions="phoneQuerySearch"
            clearable
          />
        </el-descriptions-item>
        <el-descriptions-item label="备注">
          <el-input
            v-model="remark"
            style=""
          />
        </el-descriptions-item>
        <el-descriptions-item label="提交">
          <el-button
            v-if="activeStep > 1"
            @click="handleLastStep"
          >
            上一步
          </el-button>
          <el-button
            type="primary"
            @click="handleNextStep"
          >
            {{ activeStep === 2 ? '提交审批' : '下一步' }}
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 导航按钮 -->
    <!-- <div class="action-buttons">
      <el-button
        v-if="activeStep > 1"
        @click="handleLastStep"
      >
        上一步
      </el-button>
      <el-button
        type="primary"
        @click="handleNextStep"
      >
        {{ activeStep === 2 ? '提交预约' : '下一步' }}
      </el-button>
    </div> -->
  </div>
  <!-- <el-descriptions title="User Info">
    <el-descriptions-item label="Username">kooriookami</el-descriptions-item>
    <el-descriptions-item label="Telephone">18100000000</el-descriptions-item>
    <el-descriptions-item label="Place">Suzhou</el-descriptions-item>
    <el-descriptions-item label="Remarks">
      <el-tag size="small">School</el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="Address">
      No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu Province
    </el-descriptions-item>
  </el-descriptions> -->
</template>

<script setup>
import { ref, computed, reactive, onMounted, h } from 'vue';
// import { useOrderStore } from '@/stores/order';
import { AlarmClock, DocumentAdd } from '@element-plus/icons-vue';

import { User, Coin, Check, Close } from '@element-plus/icons-vue';
import store from '@/store';
import { v4 } from 'uuid';
import { show, showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import myAxios from '@/myAxios/myAxios';
import VueCookie from 'vue-cookie';
import { dayjs } from 'element-plus';
import { useRouter } from 'vue-router';
import myAxiosWXPost from '@/myAxios/myAxiosWXPost';

import BX from '@/assets/BX.png';
import XBX from '@/assets/XBX.png';
import YJFZ from '@/assets/雅间方桌.png';
import YJYZ from '@/assets/雅间圆桌.png';
import YYTS from '@/assets/YYTS.png';
import NEW_YYTS from '@/assets/NEW_YYTS.png';
let activeName = ref('');
let handleTabClick = function (tab, event) {
  reservationDate.value = '';
  getReservationDateOptions();
};
let imgList = ref([
  YYTS,
  BX,
  XBX,
  YJYZ,
  YJYZ,
  YJFZ,
  YJFZ,
  YJFZ,
]);

let WORKID = VueCookie.get('userid');

// 包厢数据
const packages = ref([
]);

let handleDateChange = () => {
  getBxDatas();
};

let getBxDatas = () => {
  if (reservationDate.value) {
    let bx_param = `${reservationDate.value}`;
    myAxios.get('陈帅廷查询指定时间包厢使用情况', bx_param, '9900').then(res => {
      // let result = res.filter(el => !el.BX_RECORD_ID);
      let result = res;
      result.forEach(el => {
        el.ORI_FEATURES = el.FEATURES;
        el.FEATURES = JSON.parse(el.FEATURES);
        el.minGuests = Number(el.RECOMMEND.split('-')[0]);
        el.maxGuests = Number(el.RECOMMEND.split('-')[1]);
      });
      packages.value = [...result];
    });
  }
  else {
    packages.value = [];
  }

};

// 预约状态
const activeStep = ref(1);
const selectedPackage = ref(null);
const reservationDate = ref('');
const reservationTime = ref('');
const reservationTimeOptions = ref({});
const reservationDateOptions = ref([]);

function handleTimeChange ([start, end]) {
  console.log('Selected time range:', start, end);
}
// 用餐人数
const guests = ref(2);
// 客户名称
const DW = ref('');

//#region 联系人
const LXR = ref('');
const lxrOptions = ref([]);
// 联系人下拉框
const lxrQuerySearch = (queryString, cb) => {
  let options = lxrOptions.value.filter(el => el.value.includes(queryString));
  cb(options);
};
// 获取cookie中的联系人
const getLxrOptions = () => {
  let json = VueCookie.get('lxrOptions');
  if (json) {
    lxrOptions.value = JSON.parse(json);
  }
};

//#endregion

//#region 用餐部门
const YCBM1 = ref('');
const YCBM1Changed = () => {
  YCBM2.value = '';
  // YCBM2.value = YCBM_options2.value[0].value;
};
const YCBM2 = ref('');
const YCBM_oriRes = ref([]);
const YCBM_options1 = ref([]);
const YCBM_options2 = computed(() => {
  let options = YCBM_oriRes.value.filter(el => el.DEPNAME1 == YCBM1.value).map(el => {
    let option = {
      label: el.DEPNAME2,
      value: el.DEPNAME2,
    };
    return option;
  });
  // 去重
  options = options.filter((item, index, self) => {
    return self.findIndex(el => el.value === item.value) === index;
  });
  return options;
});
const getYCBM_options = () => {
  myAxios.get('陈帅廷查询食堂用餐部门', '', '9900').then(res => {
    YCBM_oriRes.value = res;

    let options = res.map(el => {
      let option = {
        label: el.DEPNAME1,
        value: el.DEPNAME1,
      };
      return option;
    });
    // 去重
    options = options.filter((item, index, self) => {
      return self.findIndex(el => el.value === item.value) === index;
    });
    YCBM_options1.value = options;

  });
};
//#endregion

//#region 审批人
let SP_ID = ref('');
const freeSpList = ref([]);
const SP_ID_oriRes = ref([]);
const SP_ID_options = computed(() => {
  let options = SP_ID_oriRes.value.filter(el => el.DEPNAME1 == YCBM1.value && el.DEPNAME2 == YCBM2.value);
  if (options.length) {
    if (freeSpList.value.some(item => item.WORKID == WORKID)) {

    }
    else {
      SP_ID.value = options[0].value;

    }

  }
  return options;
});
const getSP_ID_options = () => {
  myAxios.get('陈帅廷查询食堂包厢免审批名单', '', '9900').then(res => {
    freeSpList.value = res;
  });
  myAxios.get('陈帅廷查询食堂用餐部门审批人', '', '9900').then(res => {
    // SP_ID_oriRes.value = res;

    let options = res.map(el => {
      let option = {
        label: el.WORKID + '-' + el.NAME,
        value: el.WORKID,
        DEPNAME1: el.DEPNAME1,
        DEPNAME2: el.DEPNAME2,
      };
      return option;
    });
    // 去重
    // options = options.filter((item, index, self) => {
    //   return self.findIndex(el => el.value === item.value) === index;
    // });
    SP_ID_oriRes.value = options;
  });
};
//#endregion

//#region 成本中心
const CBZX = ref('');
const CBZX_options = ref([]);
const getCBZX_options = () => {
  CBZX_options.value = [
    {
      label: '安信',
      value: '安信',
    },
    {
      label: '海迈克动力',
      value: '海迈克动力',
    },
    {
      label: '海迈克精密',
      value: '海迈克精密',
    },
    {
      label: '驱动科技',
      value: '驱动科技',
    },
    {
      label: '斯达弗',
      value: '斯达弗',
    },
    {
      label: '海天大学',
      value: '海天大学',
    },
  ];
  // myAxios.get('陈帅廷查询食堂用餐部门', '', '9900').then(res => {
  //   // YCBM_oriRes.value = res;

  //   let options = res.map(el => {
  //     let option = {
  //       label: el.DEPNAME1,
  //       value: el.DEPNAME1,
  //     };
  //     return option;
  //   });
  //   // 去重
  //   options = options.filter((item, index, self) => {
  //     return self.findIndex(el => el.value === item.value) === index;
  //   });
  //   CBZX_options.value = options;

  // });
};
//#endregion

//#region 联系方式
const phone = ref('');
const phoneOptions = ref([]);

// 联系方式下拉框
const phoneQuerySearch = (queryString, cb) => {
  let options = phoneOptions.value.filter(el => el.value.includes(queryString));
  cb(options);
};

// 获取cookie中的联系方式
const getPhoneOptions = () => {
  let json = VueCookie.get('phoneOptions');
  if (json) {
    phoneOptions.value = JSON.parse(json);
  }
};
//#endregion

// 备注
const remark = ref('');

// 格式化时间显示
const formattedDateTime = computed(() => {
  return `${reservationDate.value} ${reservationTime.value}`;
});

// 点击包厢
const selectPackage = (pkg) => {
  if (pkg.DISABLED == '1') {
    showWarning('包厢 当前不可用，请选择包厢');
  }
  else if (pkg.BX_RECORD_ID) {
    showWarning('包厢 已被预约,请选择其他包厢');
  }
  else {
    selectedPackage.value = pkg;
    handleNextStep();
  }
};

// 上一步
const handleLastStep = async () => {
  // if (activeStep.value === 2) {
  //   reservationDateOptions.value.length = 0;
  //   reservationDate.value = '';
  // }
  activeStep.value--;
};

// 下一步
const handleNextStep = async () => {
  if (activeStep.value === 2) {
    if (validateStep()) {
      submitReservation();
    }
  }
  else if (activeStep.value === 1) {
    // let nowDate = dayjs().format('YYYY/MM/DD');
    // let record_param = `${selectedPackage.value.BX_ID}\t${nowDate}\t${WORKID}`;
    // let res = await myAxios.get('陈帅廷查询包厢预约记录', record_param, '9900');
    // getReservationDateOptions(res);
    validateStep() && activeStep.value++;
  }
  else {
    validateStep() && activeStep.value++;
  }
};

// 获取可预约时间
const getReservationDateOptions = async () => {
  let numberToDate = (num) => {
    switch (num) {
      case 1:
        return '一';
      case 2:
        return '二';
      case 3:
        return '三';
      case 4:
        return '四';
      case 5:
        return '五';
      case 6:
        return '六';
      case 0:
        return '日';
    }
  };
  reservationDateOptions.value.length = 0;
  let nowDate = dayjs();
  let startI = nowDate.hour() >= 9 ? 1 : 0;
  //蒋乐柯含能申请当天,因为有些人直接给食堂打电话,没记录,后续都通过蒋乐柯含进行申请
  if (WORKID == '19799') {
    startI = 0;
  }
  console.log('startI :>> ', startI);
  if (activeName.value == '预约') {

    //根据预约记录获取7天内的可用时间
    for (let i = startI; i <= (startI + 7); i++) {
      let newDate = nowDate.add(i, 'day');
      let date = newDate.format('YYYY/MM/DD');

      // 周六只能约中午
      let isLunchOnly = newDate.day() == 6;
      let isSunDay = newDate.day() == 0;
      if (isSunDay) {
        continue;
      }

      let tempObj = {
        value: date,
        label: date + ' 周' + numberToDate(newDate.day()),
        disabled: false,
        children: [],
      };
      tempObj.children = [
        {
          value: `${date} 11:50:00`,
          label: `${date} 中餐`,
          disabled: false,
        },
        {
          value: `${date} 17:30:00`,
          label: `${date} 晚餐`,
          disabled: false,
        },
      ];
      if (isLunchOnly) {
        tempObj.children.length = 1;
      }
      if (i == startI) {
        let dayText = '今天';
        if (i == 1) {
          dayText = '明天';
        }
        if (WORKID == '19799') {
          dayText = '今天';
          if (i == 1) {
            dayText = '明天';
          }
        }
        tempObj.label = `${dayText} 周` + numberToDate(newDate.day());
        tempObj.children[0].label = `${dayText} 中餐`;
        if (tempObj.children.length == 2) {
          tempObj.children[1].label = `${dayText} 晚餐`;
        }
      }
      else if (i == startI + 1) {
        let dayText = '后天';
        if (i == 1) {
          dayText = '明天';
        }
        if (i == 3) {
          dayText = '大后天';
        }
        tempObj.label = `${dayText} 周` + numberToDate(newDate.day());
        tempObj.children[0].label = `${dayText} 中餐`;
        if (tempObj.children.length == 2) {
          tempObj.children[1].label = `${dayText} 晚餐`;
        }
      }
      reservationDateOptions.value.push(tempObj);
    }
  }
  else if (activeName.value == '补录') {

    //根据预约记录获取过去30天内的可用时间
    for (let i = 0; i <= (startI + 30); i++) {
      let newDate = nowDate.add(-i, 'day');
      let date = newDate.format('YYYY/MM/DD');

      // 周六只能约中午
      let isLunchOnly = newDate.day() == 6;
      let isSunDay = newDate.day() == 0;
      if (isSunDay) {
        continue;
      }

      let tempObj = {
        value: date,
        label: date + ' 周' + numberToDate(newDate.day()),
        disabled: false,
        children: [],
      };
      tempObj.children = [
        {
          value: `${date} 11:50:00`,
          label: `${date} 中餐`,
          disabled: false,
        },
        {
          value: `${date} 17:30:00`,
          label: `${date} 晚餐`,
          disabled: false,
        },
      ];
      if (isLunchOnly) {
        tempObj.children.length = 1;
      }
      reservationDateOptions.value.push(tempObj);
    }
  }
};


let router = useRouter();

// 提交预约
const submitReservation = async () => {
  //   let row = dialogDatas.currentData;
  let BX_RECORD_ID = v4();
  let BX_ID = selectedPackage.value.BX_ID;
  let BX_NAME = selectedPackage.value.NAME;
  let BX_BZ = selectedPackage.value.BX_BZ;
  let RECORD_TIME = reservationDate.value;
  let CAPACITY = guests.value;
  let newDw = DW.value;
  let newLXR = LXR.value;
  let newYCBM = YCBM1.value + '-' + YCBM2.value;
  let newCBZX = CBZX.value;
  let PHONE = phone.value;
  let REMARK = remark.value;
  let STATE = '待审核';
  let NAME = VueCookie.get('username');
  // let spList = await myAxios.get('陈帅廷查询食堂包厢免审批名单', ``, '9900');
  // let SP_ID = ``;
  // if (spList.length > 0) {
  //   SP_ID.value = spList[0].MANAGERID1;
  // }
  if (freeSpList.value.some(item => item.WORKID == WORKID)) {
    STATE = '已审核';
  }
  let title = `您有新的餐厅预约` + (activeName.value == '补录' ? `--已完成用餐，补审批` : ``);
  let msg =
    `<div>` + `${title}\r\n` + `</div>`
    + `<div>` + `包厢: ${BX_NAME}\r\n` + `</div>`
    + `<div style="color:red">` + `日期: ${RECORD_TIME.replace('11:50:00', '').replace('17:30:00', '')}\r\n` + `</div>`
    + `<div style="color:red">` + `用餐时间: ${RECORD_TIME.includes('11:50:00') ? '11:50-13:00' : '17:30-20:00'}\r\n` + `</div>`
    + `<div>` + `人数: ${CAPACITY}\r\n` + `</div>`
    + `<div>` + `消费标准: ${BX_BZ}\r\n` + `</div>`
    + `<div>` + `客户名称: ${newDw}\r\n` + `</div>`
    + `<div>` + `用餐部门: ${newYCBM}\r\n` + `</div>`
    + `<div>` + `联系人: ${newLXR}\r\n` + `</div>`
    + `<div>` + `联系方式: ${PHONE}\r\n` + `</div>`
    + `<div>` + `备注: ${REMARK}\r\n` + `</div>`;
  msg = msg.replace(/null/g, '').replace(/undefined/g, '');
  // let pushRes = await myAxios.postToWeChatText(order.WORKID, msg, msg);

  ElMessageBox.confirm(
    msg,
    '提醒',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).then(() => {
    let params = `${BX_RECORD_ID}\t${BX_ID}\t${RECORD_TIME}`
      + `\t${WORKID}\t${CAPACITY}\t${PHONE}\t${STATE}`
      + `\t${''}\t${REMARK}\t${SP_ID.value}\t${BX_BZ}\t${newDw}`
      + `\t${newLXR}\t${newYCBM}\t${newCBZX}`;
    myAxios.post('陈帅廷添加或修改食堂包厢记录', params).then(async res => {
      if (res.includes('成功')) {
        phoneOptions.value = [{ value: phone.value }];
        VueCookie.set('phoneOptions', JSON.stringify(phoneOptions.value));
        lxrOptions.value = [{ value: LXR.value }];
        VueCookie.set('lxrOptions', JSON.stringify(lxrOptions.value));

        showSuccess('提交成功!' + res);
        if (STATE == '待审核') {
          // SP_ID = '14602';
          let spTitle = `您有新的待审批食堂包厢申请` + (activeName.value == '补录' ? `--已完成用餐，补审批` : ``);

          let result = await myAxios.postToWeChat(SP_ID.value, spTitle, `${NAME}申请 包厢:${BX_NAME},时间:${RECORD_TIME} 请及时审批`
            , `http://htqdds.haitian.com:9911/qdmes/CHER/driver_order_menu/dist/index.html#/roomHistory?BX_RECORD_ID=${BX_RECORD_ID}`);
          showSuccess('发送成功!' + result);
        }
        else if (STATE = '已审核') {
          let order = {
            BX_ID: BX_ID,
            RECORD_TIME: RECORD_TIME,
            USERNAME: NAME,
            BX_RECORD_ID: BX_RECORD_ID,
            WORKID: WORKID,
          };
          SendTemplate_WX(order);
        };
        router.push({ path: '/roomHistory', query: { BX_RECORD_ID: BX_RECORD_ID } });
      }
      else {
        showWarning('更新失败res!' + res);
      }
    }).catch((err) => {
      showWarning('更新失败err!' + err);
    });
  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      });
    });


};
const bxName = (id) => {
  let bxItem = packages.value.find(item => item.BX_ID == id);
  if (bxItem) {
    return bxItem.NAME;
  }
  else {
    return id;
  }
};
const SendTemplate_WX = (order, isSuccess = true) => {
  let BX_NAME = bxName(order.BX_ID);
  let RECORD_TIME = order.RECORD_TIME;
  let NAME = order.USERNAME;
  let url = `http://smart.haitian.com/Cheresting/driver_order_menu/dist/index.html#/roomHistory`
    + `?BX_RECORD_ID=${order.BX_RECORD_ID}`;
  let content = {
    'openId': 'ok-KS08CgnvAOLKnALEL142tsqYk',
    'url': url,
    'title': `${BX_NAME}`,
    'data1': `${BX_NAME}`,
    'data2': `${RECORD_TIME}`,
    'data3': `${order.WORKID} ${NAME}`,
    // 'description': '外卖订单/包厢订单',
    // 'picurl': '11',
    'remark': '请及时接收',
    'tokenname': 'ACCESS_TOKEN_WX_QDFW'
  };
  myAxiosWXPost.post(`http://192.168.100.28:85/WorkWxMsgService/WxWorkMsgService.asmx`,
    `SendTemplate_WX`, content)
    .then(pushRes => {
      if (pushRes.includes('成功')) {
        let nowStr = dayjs().format('YYYY/MM/DD HH:mm:ss');
        myAxios.post('陈帅廷更新食堂包厢记录推送时间', `${order.BX_RECORD_ID}\t${nowStr}`);
      }
      console.log('pushRes :>> ', pushRes);
    });
};

// 审核数据完整性
const validateStep = () => {
  switch (activeStep.value) {
    case 1:
      if (!selectedPackage.value) {
        showWarning('请选择包厢类型');
        return false;
      }
      if (!reservationDate.value) {
        showWarning('请选择完整的时间');
        return false;
      }
      return true;
    case 2:
      if (!phone.value) {
        showWarning('请输入联系方式');
        return false;
      }
      else {
        const phoneReg = /^1[3456789]\d{9}$/;
        if (!phoneReg.test(phone.value)) {
          showWarning('手机号不合法,请输入正确的手机号');
          return false;
        }
      }

      if (!selectedPackage.value.BX_BZ) {
        showWarning('请选择消费标准');
        return false;
      }

      if (!DW.value) {
        showWarning('请输入客户名称');
        return false;
      }

      if (!LXR.value) {
        showWarning('请输入联系人员');
        return false;
      }

      if ((!YCBM1.value) || (!YCBM2.value)) {
        if (freeSpList.value.some(item => item.WORKID == WORKID)) {
        }
        else {
          showWarning('请选择用餐部门');
          return false;
        }
      }

      if (!SP_ID.value) {
        // 表里的人不用审批人，直接通过
        if (freeSpList.value.some(item => item.WORKID == WORKID)) {
        }
        else {
          showWarning('请选择审批人');
          return false;
        }
      }

      if (!CBZX.value) {
        showWarning('请选择成本中心');
        return false;
      }

      return true;
    case 3:
    // if (!phone.value) {
    //   showWarning('请输入联系方式');
    //   return false;
    // }
    // else {
    //   const phoneReg = /^1[3456789]\d{9}$/;
    //   if (!phoneReg.test(phone.value)) {
    //     showWarning('手机号不合法,请输入正确的手机号');
    //     return false;
    //   }
    // }
    // return true;
    default:
      return true;
  }
};


onMounted(() => {
  getBxDatas();
  getReservationDateOptions();
  getYCBM_options();
  getSP_ID_options();
  getCBZX_options();

  getLxrOptions();
  getPhoneOptions();

  ElMessageBox({
    title: '温馨提示',
    confirmButtonClass: 'selfConfirmButtonClass',
    message: h('p', null, [
      h('img', { src: YYTS, style: { width: '100%' } },)
      // h('h3', { style: { textAlign: 'center' } }, '预约说明'),
      // h('ol', { style: { paddingLeft: '20px', fontSize: '14px' } }, [
      //   h('li', null, '营业时间: 每周工作日和周六中餐'),
      //   h('li', null, '开餐时间: 中午11:50-13:00,晚上17:30-20:00'),
      //   h('li', null, '餐厅入口: 驱动食堂东北门'),
      //   h('li', null, '关于酒水: 食堂提供饮料和啤酒(费用另结算)其他酒水,须自行携带'),
      //   h('li', null, '预约时间: 至少提前一天,17:00截止,当天不受理'),
      // ]),
      // h('div', { style: { paddingLeft: '20px' } }, '联系方式：屈经理（651018,13566511216）'),
    ]),
    callback: () => {
    },
  });
});

</script>

<style>
.el-message-box__title {
  font-size: 13px;
}
.selfConfirmButtonClass {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}
.selfConfirmButtonClass:hover {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}
.selfConfirmButtonClass:focus-visible {
  background-color: white !important;
  border-color: #dcdfe6;
  color: rgb(0, 53, 140);
}

.reservation-system {
  max-width: 1200px;
  margin: 0 auto;
  padding: 10px;
}

.steps {
  margin-bottom: 40px;
}

.package-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.package-card {
  cursor: pointer;
  transition: all 0.3s;
}

.package-card.disabled {
  cursor: not-allowed;
  transition: all 0.3s;
  border: 1px solid red;
}

.package-card.selected {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 12px rgba(var(--el-color-primary-rgb), 0.1);
}

.package-content {
  padding: 15px;
}

.package-details {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 15px;
  margin: 10px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: var(--el-text-color-secondary);
}

.feature-tag {
  margin: 5px 5px 0 0;
}

.datetime-picker {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-bottom: 30px;
}

.time-slots {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 10px;
}

.time-tag {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .package-grid {
    grid-template-columns: 1fr;
  }

  .datetime-picker {
    flex-direction: column;
  }
}

.home-container {
  min-height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.entry-card {
  width: 100%;
  max-width: 800px;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.logo {
  text-align: center;
  margin-bottom: 40px;
  color: #2c3e50;
}

.logo h1 {
  font-size: 2.5rem;
  margin: 0;
}

.button-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  padding: 0px;
  margin-top: 10px;
}

.action-button {
  height: 180px;
  width: 100%;
  border-radius: 15px;
  transition: all 0.3s ease;
  margin-left: 0px !important;
}

.action-button:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.button-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.icon {
  font-size: 3.5rem !important;
  margin-bottom: 15px;
}

.button-text h2 {
  margin: 10px 0;
  font-size: 1.8rem;
}

.button-text p {
  margin: 0;
  color: #666;
  font-size: 1rem;
}

@media (max-width: 768px) {
  .logo h1 {
    font-size: 2rem;
  }

  .button-group {
    grid-template-columns: 1fr;
  }

  .action-button {
    height: 150px;
  }

  .icon {
    font-size: 2.5rem !important;
  }

  .button-text h2 {
    font-size: 1.5rem;
  }
}
</style>